package com.zsxb.crm.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zsxb.crm.dto.AddUserDTO;
import com.zsxb.crm.dto.PageDTO;
import com.zsxb.crm.dto.UserPageDTO;
import com.zsxb.crm.mapper.DeptMapper;
import com.zsxb.crm.mapper.RoleMapper;
import com.zsxb.crm.mapper.TransferMapper;
import com.zsxb.crm.mapper.UserMapper;
import com.zsxb.crm.pojo.Dept;
import com.zsxb.crm.pojo.Role;
import com.zsxb.crm.pojo.Transfer;
import com.zsxb.crm.pojo.User;
import com.zsxb.crm.result.PageResult;
import com.zsxb.crm.result.UserResult;
import com.zsxb.crm.service.UserService;
import com.zsxb.crm.vo.UserListSelectVO;
import com.zsxb.crm.vo.UserDeptVO;
import com.zsxb.crm.vo.UserVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final DeptMapper deptMapper;
    private final RoleMapper roleMapper;
    private final TransferMapper transferMapper;

    /**
     * 用户分页查询
     *
     * @param pageDto
     * @return
     */
    @Override
    @Transactional
    public PageResult pageUser(UserPageDTO pageDto) {
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        PageResult pageResult = new PageResult();
        Page<User> pageUser = userMapper.pageUser(pageDto);
        log.info("分页查询结果：{}", pageUser);
        List<User> result = pageUser.getResult();
        result.forEach(u -> {
            Dept dept = deptMapper.getById(u.getDeptId());
            u.setDept(dept);
        });
        pageResult.setTotal(pageUser.getTotal());
        pageResult.setRows(result);
        return pageResult;
    }

    /**
     * 新增用户
     */
    @Override
    public User addUser(AddUserDTO addUserDTO) {
        String strRoleIds = addUserDTO.getRoleIds().toString();
        userMapper.addUser(addUserDTO, strRoleIds);
        //更新userId
        userMapper.updateId(addUserDTO.getId());
        Long newId = addUserDTO.getId();
        log.info("新增用户：{}", newId);
        return userMapper.getById(newId);
    }

    /**
     * 修改用户
     *
     * @param addUserDTO
     */
    @Override
    public void updataUser(AddUserDTO addUserDTO) {
        User user = new User();
        BeanUtils.copyProperties(addUserDTO, user);
        String roleIds ="[" + StringUtils.join(addUserDTO.getRoleIds(),",") + "]";
        user.setRoleIds(roleIds);
        userMapper.updataUser(user);
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public UserResult getById(Long id) {
        User user = userMapper.getById(id);
        UserVo userVO = new UserVo();
        BeanUtils.copyProperties(user, userVO);
        List<Integer> integers = getList(user.getRoleIds());
        List<Role> listRoles = new ArrayList<>();
        integers.forEach(i->{
            Role role = roleMapper.selectById(i);
            listRoles.add(role);
        });
        userVO.setRoles(listRoles);
        List<Role> allRoles = roleMapper.allRoles();
        Dept byId = deptMapper.getById(user.getDeptId());
        userVO.setDept(deptMapper.getById(user.getDeptId()));
        return UserResult.success(userVO,integers,allRoles);
    }

    /**
     * 批量删除用户
     * @param ids
     */
    @Override
    public void delByIds(String ids) {
        //[1,2,3,4,5]
        String[] split = ids.split(",");
        userMapper.delByIds(split);

    }


    /**
     * 重置密码
     * @param user
     */
    @Override
    public void resetPwd(User user) {
        userMapper.updataUser(user);
    }

    @Override
    public List<UserListSelectVO> listselect(Long deptId) {
        List<UserListSelectVO> userListSelectVO = userMapper.listselect(deptId);
        return userListSelectVO;
    }

    /**
     * 部门id查询员工
     *
     * @param deptId
     * @return
     */
    @Override
    public ArrayList<UserDeptVO> getUserDept(Long deptId) {
         //通过部门id，查询所有部门id
        List<Dept> deptIds = deptMapper.getDeptLists(deptId);
        //查询关联了部门的员工
        ArrayList<UserDeptVO> arrayList = new ArrayList<>();

        for (Dept id : deptIds) {
            //复制员工信息

            UserDeptVO userList = userMapper.getUser(id.getDeptId());
            if (userList != null) {
                //查询员工关联的部门
                userList.setDept(deptMapper.getDept(id.getDeptId()));
                arrayList.add(userList);
            }
        }
       return arrayList;

    }

    /**
     * 将字符串转换为list
     * @param str
     * @return
     */
    private static List getList(String str) {
        if (str == null) {
            // 处理 str 为 null 的情况，例如返回空列表
            return Collections.emptyList();
        }
        int length = str.length();
        List<Integer> index = new ArrayList<>(length);
        for (int i = 1; i <= length - 2; i=i+2) {
            index.add(Integer.valueOf(str.substring(i, i + 1)));
        }
        return index;
    }
}
